<?php
/**
 * Created by PhpStorm.
 * User: liuhongchuan
 * Date: 2018/6/14
 * Time: 18:28
 */
namespace App\Http\Controllers\Api;

use App\Http\Controllers\ApiController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CookBookController extends ApiController
{
    /**
     * 食谱列表
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        $group_type = $request->input("type", 1);
        $page = $request->input("page", 1);
        $limit = $request->input("limit", 10);

        if (!in_array($group_type, array(1, 2))) { //套餐类型；1减脂 2增肌
            return $this->failed("参数错误");
        }
        if ($page <= 0) {
            return $this->failed("参数错误");
        }
        if ($limit <= 0 || $limit > 100) {
            return $this->failed("参数错误");
        }
        $cookbook_list = DB::table('cookbooks')
            ->where(['status' => 1, 'group_type' => $group_type])
            ->select('id', 'title', 'main_pic', 'desc')
            ->skip($limit * ($page -1))
            ->take($limit)
            ->get();
        $count =  DB::table('cookbooks')->where(['status' => 1, 'group_type' => $group_type])->count();
        return $this->success(['cookbooks' => empty($cookbook_list) ? [] : $cookbook_list,  'more' => $count > $page * $limit ? true : false]);
    }

    /**
     * 食谱详情
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function detail(Request $request) {
        $id = $request->input('id');
        if ($id <= 0) {
            return $this->failed("参数错误");
        }

        $cookbook = DB::table('cookbooks')->where(['id' => $id, 'status' => 1])->select('id', 'title', 'main_pic', 'content')->first();
        if (empty($cookbook)) {
            return $this->failed("参数错误");
        }
        return $this->success(['cookbook' => $cookbook]);
    }
}